using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using Imtihan.Web;
using System.ServiceModel.DomainServices.Client;

namespace Imtihan
{
    public partial class Login : Page
    {
        ImtihanDomainContext _context = new ImtihanDomainContext();
        public Login()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            submit();
        }

        private void submit()
        {
            _context.GetUserByIdAndPassword(tbUsername.Text, tbPassword.Password, (op) =>
            {
                if (!op.HasError && op.Value != null)
                {
                    UserManager.Instance = op.Value;

                    _context.GetUserRolesByUserId(tbUsername.Text, (opUserRoles) =>
                    {
                        if (!opUserRoles.HasError && opUserRoles.Value != null)
                        {
                            UserManager.Roles = opUserRoles.Value;
                            this.NavigationService.Navigate(new Uri("/Home", UriKind.Relative));
                        }

                    }, null);

                }
                else
                {
                    MessageBox.Show("Invalid username or password");
                }
            }, null);
        }

        private void tbUsername_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                submit();
            }
        }
    }
}
